import React from 'react';
import { connect } from 'react-redux';
import { List,Badge } from 'antd-mobile';


@connect(
state => state
)
class Message extends React.Component{
	getLast(arr){
		return arr[arr.length -1];
	}
	render(){
		let msgGroup = {};
		this.props.chat.chatmsg.forEach(v => {
			msgGroup[v.chatid] = msgGroup[v.chatid] || [];
			msgGroup[v.chatid].push(v);
		});
		const msgGroupArray = Object.values(msgGroup).sort((a,b) =>{
			return this.getLast(b).create_time - this.getLast(a).create_time;
		});
		const userid = this.props.user._id;
		const users = this.props.chat.users;
		return(
			<div id='message-page'>
				{
					msgGroupArray.map(v => {
						const lastItem = this.getLast(v);
						const targetUserid = lastItem.from === userid ? lastItem.to :lastItem.from;
						const unreadNumber = v.filter(n => !n.read && n.to === userid ).length;
						return (
							<List 
								key={lastItem._id} 
								onClick={() =>{
									this.props.history.push(`/chat/${targetUserid}`);
								}}
							>
								<List.Item
									arrow='horizontal'
									extra={<Badge text={unreadNumber}></Badge>}
									thumb={require(`../img/${users[targetUserid].avatar}.jpg`)} 
								>
									{lastItem.content}
									<List.Item.Brief>{users[targetUserid].user}</List.Item.Brief>
								</List.Item>
							</List>
						)
					})
				}
			</div>
		)
	}
}

export default Message